<template>
  <div>
    <!-- 三级分类联动的公共组件 -->
    <Category :disable="!isAttrList"/>

    <el-card
      v-if="isAttrList"
      shadow="always"
      :body-style="{ padding: '20px' }"
      :style="{ marginTop: '20px' }"
    >
      <template #header>
        <el-button
          type="primary"
          icon="ele-Plus"
          @click="addAttr"
          :disabled="!category3Id"
          >添加属性</el-button
        >
      </template>
      <!-- card body -->
      <el-table :data="attrList" border stripe>
        <el-table-column type="index" width="80" label="序号" />
        <el-table-column
          label="属性名称"
          width="180"
          prop="attrName"
        ></el-table-column>
        <el-table-column label="属性值名称列表">
          <template v-slot="{ row }">
            <el-tag
              :style="{ marginLeft: '10px' }"
              type="success"
              v-for="item in row.attrValueList"
              :key="item.id"
              >{{ item.valueName }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template v-slot="{ row }">
            <el-button
              type="warning"
              size="small"
              icon="ele-Edit"
              @click="updateAttr(row)"
            ></el-button>
            <el-popconfirm
              title="你确定删除当前的属性吗?"
              @confirm="deleteAttr(row.id)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="small"
                  icon="ele-Delete"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card
      v-else
      shadow="always"
      :body-style="{ padding: '20px' }"
      :style="{ marginTop: '20px' }"
    >
      <el-form label-width="80px" :inline="true" size="default">
        <el-form-item label="属性名">
          <el-input
            placeholder="请输入属性名"
            v-model="newAttrInfo.attrName"
          ></el-input>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" size="default" @click="addAttrValue"
          >添加属性值</el-button
        >
        <el-button size="default" @click="">取消</el-button>
      </div>
      <el-table
        :data="newAttrInfo.attrValueList"
        border
        stripe
        :style="{ margin: '20px 0' }"
      >
        <el-table-column type="index" width="80" label="序号" />
        <el-table-column label="属性值名称">
          <template v-slot="{ row, $index }">
            <el-input
              ref="editIpt"
              v-if="row.isEdit"
              v-model="row.valueName"
              placeholder="请输入属性值"
              size="small"
              @blur="toLook(row, $index)"
            ></el-input>
            <div v-else @click="toEdit(row)">{{ row.valueName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ $index }">
            <el-button
              type="danger"
              size="small"
              @click="deleteAttrValue($index)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div>
        <el-button
          type="primary"
          @click="save"
          :disabled="
            newAttrInfo.attrName === '' ||
            newAttrInfo.attrValueList.length === 0
          "
          >保存</el-button
        >
        <el-button @click="isAttrList = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "Attr",
});
</script>

<script setup lang="ts">
import { nextTick, ref, watch } from "vue";
import { storeToRefs } from "pinia";
import { cloneDeep } from "lodash";
import {
  reqAttrList,
  reqAddOrUpdateAttr,
  reqDeleteAttr,
  type attrValueItemType,
} from "@/api/attr";
import type {
  attrListType,
  addOrUpdateAttrParamType,
  attrItemType,
} from "@/api/attr";
import useCategoryStore from "@/stores/category";

//得到category的pinia中的store对象
const categoryStore = useCategoryStore();

//从pinia中拿到category的3个id,用来请求列表
const { category1Id, category2Id, category3Id } = storeToRefs(categoryStore);

// console.log(category1Id, category2Id, category3Id);

//设置一个保存平台属性的数据
const attrList = ref<attrListType>([]);

//封装一个请求平台属性列表的函数
const getAttrList = async () => {
  //发送请求
  const result = await reqAttrList(
    category1Id.value as number,
    category2Id.value as number,
    category3Id.value as number
  );
  //把得到的结果赋值给数据保存
  attrList.value = result;
};

//监听category3Id,改变以后才能发送请求
watch(category3Id, (newVal) => {
  //如果category3Id变成null的时候,是不会发送请求的,并且要清空当前的属性列表
  if (!newVal) {
    attrList.value = [];
    return;
  }
  //发送请求
  getAttrList();
});

//定义一个响应式数据,代表当前展示的是列表还是新增的结构
const isAttrList = ref(true);

//定义一个修改或者新增的 请求体对象, 用来收集好数据之后,进行发送请求
const newAttrInfo = ref<addOrUpdateAttrParamType>({
  attrName: "",
  categoryId: category3Id.value as number,
  categoryLevel: 3,
  attrValueList: [],
});

//定义一个数据获得页面中存在的那个input的元素
const editIpt = ref();

//添加属性按钮的事件回调函数
const addAttr = () => {
  isAttrList.value = false;
  //先清空数据,以防止之前的数据出现
  newAttrInfo.value = {
    attrName: "",
    categoryId: category3Id.value as number,
    categoryLevel: 3,
    attrValueList: [],
  };
};

//添加属性值按钮的事件回调函数
const addAttrValue = () => {
  newAttrInfo.value.categoryId = category3Id.value as number;
  //先向属性值列表中添加一个数据，让table生成一条数据，可以新增属性值
  newAttrInfo.value.attrValueList.push({
    valueName: "",
    isEdit: true, //是否是编辑模式
  });

  //让table中的input自动获取焦点
  //数据虽然改变了,但是视图还是没有更新好呢,所以要使用nextTick方法(等下一次的DOM更新完成以后执行回调函数)
  nextTick(() => {
    editIpt.value.focus();
  });
};

//当新增属性值的input失去焦点(编辑模式--查看模式)的事件回调函数
const toLook = (row: attrValueItemType, index: number) => {
  row.isEdit = false;

  //判断输入的内容是否为空,如果为空,则删除当前新的属性值数据
  if (!row.valueName) {
    newAttrInfo.value.attrValueList.splice(index, 1);
  }

  //判断输入的内容是否重复,如果重复也要删除
  const isRepeat = newAttrInfo.value.attrValueList.some((item) => {
    //先排除自己和自己比较
    if (item === row) return;
    //如果其他人和自己比较有相等的 则直接返回true
    return item.valueName === row.valueName;
  });
  //如果有重复的,则删除当前数据
  if (isRepeat) {
    newAttrInfo.value.attrValueList.splice(index, 1);
  }
};

//当点击属性值的时候 切换到input（查看模式--编辑模式）的事件回调函数
const toEdit = (row: attrValueItemType) => {
  row.isEdit = true;
  //切换到编辑模式的时候,需要让input主动的获取焦点
  nextTick(() => {
    editIpt.value.focus();
  });
};

//删除某个属性值的事件回调函数
const deleteAttrValue = (index: number) => {
  newAttrInfo.value.attrValueList.splice(index, 1);
};

//修改属性值列表 事件回调函数
const updateAttr = (row: attrItemType) => {
  newAttrInfo.value.categoryId = category3Id.value as number;
  //回填数据
  newAttrInfo.value = cloneDeep(row);
  newAttrInfo.value.attrValueList.forEach((item) => (item.isEdit = false));
  //打开新增或修改的视图
  isAttrList.value = false;
};

//修改或者新增的提交
const save = async () => {
  //整理参数

  //提交
  await reqAddOrUpdateAttr(newAttrInfo.value);

  //保存完成后切换到列表展示
  isAttrList.value = true;

  //重新加载数据
  getAttrList();
};

//删除某个平台属性
const deleteAttr = async (id: number) => {
  await reqDeleteAttr(id);
  ElMessage.success("删除平台属性成功");

  //重新加载数据
  getAttrList();
};
</script>

<style scoped lang="scss"></style>
